package cn.edu.ljl;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Writer;
import java.sql.SQLException;
import java.util.List;

//对成绩信息进行修改
//修改成功后、进入成绩展示界面，使用list

public class Edit extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        this.doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String id = request.getParameter("id");

        String sql = "SELECT * FROM grade WHERE id=" + id;
        try {
            List<Student> students = DBMS.getStudents(sql);
            if (students.size() == 0) {
                response.sendRedirect("./list");
                return;
            }

            Student student = students.get(0);

            StringBuilder sb = new StringBuilder();
            sb.append(Page.getHeader());
            sb.append(buildStudentForm(student));
            sb.append(Page.getEnd());

            response.setCharacterEncoding("UTF-8");
            try (Writer writer = response.getWriter()) {
                writer.write(sb.toString());
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public String buildStudentForm(Student student) {
        String html = String.format("<center>\n" +
                        "<br>\n" +
                        "<form action='./updateBook' method='POST''>\n" +
                        "<input type='hidden' name='id' value='%s'>" +
                        "<table style='background-color:#dddddd;padding:2em'>\n" +
                        "\t<tr><td>学号:</td><td><input type='text' name=numbb    value='%s'></td></tr>\n" +
                        "\t<tr><td>名字:</td><td><input type='text' name=nam      value='%s'></td></tr>\n" +
                        "\t<tr><td>科目:</td><td><input type='text' name=subje    value='%s'></td></tr>\n" +
                        "\t<tr><td>分数:</td><td><input type='text' name=score    value='%s'></td></tr>\n"+
                        "\t<tr><td>感想:</td><td><textarea name=fell cols='50' rows='5'>%s</textarea></td></tr>\n" +
                        "\t<tr><td colspan='2' align='center'><br><input type='submit' value='提交修改'></td></tr>\n" +
                        "</table>\t\n" +
                        "</form>\n" +
                        "</div>\n" +
                        "</center>",
                student.getNumber(), student.getName(), student.getSubject(), student.getScore(), student.getFeel()
        );
        return html;
    }
}
